﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace JML.Core.DI
{
    public class DisposableAction<T> : IDisposable
    {
        readonly Action<T> _action;
        readonly T _value;

        public DisposableAction(Action<T> actionToExecuteOnDispose, T value)
        {
            _VerifyDisposeActionIsDefined(actionToExecuteOnDispose);

            _action = actionToExecuteOnDispose;
            _value = value;
        }

        public DisposableAction(Action<T> actionToExecuteOnStart, Action<T> actionToExecuteOnDispose, T value)
        {
            _VerifyDisposeActionIsDefined(actionToExecuteOnDispose);

            _action = actionToExecuteOnDispose;
            _value = value;

            actionToExecuteOnStart(_value);
        }

        public T Value
        {
            get { return _value; }
        }
        public void Dispose()
        {
            _action(_value);
        }
        private void _VerifyDisposeActionIsDefined(Action<T> action)
        {
            if (action == null) throw new ArgumentNullException("action");
        }
    }

    public class DisposableAction : IDisposable
    {
        Action _action;

        public DisposableAction(Action actionToExecuteOnDispose)
        {
            _VerifyDisposeActionIsDefined(actionToExecuteOnDispose);

            _action = actionToExecuteOnDispose;
        }
        public DisposableAction(Action actionToExecuteOnStart, Action actionToExecuteOnDispose)
        {
            _VerifyDisposeActionIsDefined(actionToExecuteOnDispose);

            _action = actionToExecuteOnDispose;

            actionToExecuteOnStart();
        }

        public void Dispose()
        {
            _action();
        }

        private void _VerifyDisposeActionIsDefined(Action action)
        {
            if (action == null) throw new ArgumentNullException("action");
        }
    }

}
